package pikes.samples.countries.ui.peak;

import java.util.Map;

import org.springframework.web.servlet.support.RequestContext;

import pikes.core.Printable;
import pikes.ecma.Addition;
import pikes.ecma.IAdditiveExpression;
import pikes.ecma.IMultiplicativeExpression;
import pikes.ecma.IPrimaryExpression;
import pikes.ecma.Identifier;
import pikes.ecma.StringLiteral;
import pikes.peak.RequestIndependentProperty;
import pikes.peak.RequestProperty;

public class DynamicAddition implements RequestProperty<Addition> {

	private RequestProperty<? extends IAdditiveExpression> first = null;

	private RequestProperty<? extends IMultiplicativeExpression> second = null;

	public DynamicAddition(CharSequence firstIdentifier, CharSequence secondIdentifier) {
		this(new Identifier(firstIdentifier), new Identifier(secondIdentifier));
	}

	public DynamicAddition(RequestProperty<? extends Printable> literal, CharSequence secondIdentifier) {
		this(new RequestDependentLiteral(literal), new RequestIndependentProperty<IMultiplicativeExpression>(
				new Identifier(secondIdentifier)));
	}

	public DynamicAddition(IAdditiveExpression first, IMultiplicativeExpression second) {
		this(new RequestIndependentProperty<IAdditiveExpression>(first),
				new RequestIndependentProperty<IMultiplicativeExpression>(second));
	}

	public DynamicAddition(RequestProperty<? extends IAdditiveExpression> first,
			RequestProperty<? extends IMultiplicativeExpression> second) {
		this.first = first;
		this.second = second;
	}

	public Addition getValue(Map model, RequestContext requestContext) throws Exception {
		return new Addition(first.getValue(model, requestContext), second.getValue(model, requestContext));
	}

}

class RequestDependentLiteral implements RequestProperty<IPrimaryExpression> {

	private RequestProperty<? extends Printable> literal = null;

	public RequestDependentLiteral(RequestProperty<? extends Printable> literal) {
		this.literal = literal;
	}

	public IPrimaryExpression getValue(Map model, RequestContext requestContext) throws Exception {
		return new StringLiteral(literal.getValue(model, requestContext));
	}

}